package com.cn.ZhiKeDianShang;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.cn.ZhiKeDianShang.base.BaseActivity;
import com.cn.ZhiKeDianShang.model.CheckUpdateBean;
import com.cn.ZhiKeDianShang.presenter.ChoiceAnchorsPresenter;
import com.cn.ZhiKeDianShang.presenter.view.ChoiceAnchorsView;
import com.cn.ZhiKeDianShang.ui.activity.LoginRegisterResult;
import com.cn.ZhiKeDianShang.ui.activity.ReclarationActivity;
import com.cn.ZhiKeDianShang.ui.fragment.HomeFragment;
import com.cn.ZhiKeDianShang.ui.fragment.MineFragment;
import com.cn.ZhiKeDianShang.util.AndroidUtil;
import com.cn.ZhiKeDianShang.util.ProgressDialogFragment;
import com.cn.ZhiKeDianShang.util.StatusBarUtil;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.ObjectResult;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.result.Result;
import com.hailong.appupdate.AppUpdateManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.functions.Consumer;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/1/2.
 */

public class MainActivity extends BaseActivity<ChoiceAnchorsView, ChoiceAnchorsPresenter> implements ChoiceAnchorsView {

    @BindView(R.id.nav_home_img)
    ImageView navHomeImg;
    @BindView(R.id.nav_home_text)
    TextView navHomeText;
    @BindView(R.id.nav_home_tab)
    RelativeLayout navHomeTab;
    @BindView(R.id.nav_mine_img)
    ImageView navMineImg;
    @BindView(R.id.nav_mine_text)
    TextView navMineText;
    @BindView(R.id.nav_mine_tab)
    RelativeLayout navMineTab;

    @BindView(R.id.nav_todaypolicy_img)
    ImageView navTodaypolicyImg;
    @BindView(R.id.nav_todaypolicy_text)
    TextView navTodaypolicyText;
    @BindView(R.id.nav_todaypolicy_tab)
    RelativeLayout navTodaypolicyTab;


    private ProgressDialogFragment mProgressDialog;
    //手机连续按返回键两次的间隔时间
    private long mExitTime;
    private static final String[] FRAGMENT_TAG = {"mBossFragment", "mNewsFragment"};
    private static final String PRV_SELINDEX = "PREV_SELINDEX";
    private int selindex = 0;

    private HomeFragment mHomeFragment;
    private MineFragment mMineFragment;


    AnimationDrawable animation1;

    public MainActivity() {

    }

    private void initPermission() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(
                Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.ACCESS_FINE_LOCATION
                , Manifest.permission.READ_PHONE_STATE
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {

                } else {
                    //只要有一个权限被拒绝，就会执行
                    Toast.makeText(MainActivity.this, "未授权权限，部分功能不能使用", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("Debug", "到达oncreate中------------");
        setSelect(selindex);
        initPermission();
//        int i = AndroidUtil.compareVersion("1.0.2", "1.0.1.1");
//        Log.d("Debug","版本对比"+i);
        checkUpdate();
        getOss();
    }


    /**
     * @param
     */
    private void getOss() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        params.put("verify", "eL1LJU7dOdjYmqMI");

        HttpUtils.post().url(AppConfig.COMMON_GETOSS)
                .params(params)
                .addSecret()
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {
                    @Override
                    public void onResponse(ObjectResult<LoginRegisterResult> result) {
//                        DialogHelper.dismissProgressDialog();
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    /**
     * @param
     */
    private void checkUpdate() {
//        DialogHelper
        Map<String, String> params = new HashMap<>();
        HttpUtils.post().url(AppConfig.COMMON_VERSION)
                .params(params)
                .build()
                .execute(new BaseCallback<CheckUpdateBean>(CheckUpdateBean.class) {
                    @Override
                    public void onResponse(ObjectResult<CheckUpdateBean> result) {
//                        DialogHelper.dismissProgressDialog();
                        Log.d("Debug", "到达请求这里---");
                        if (Result.checkSuccess(MainActivity.this, result)) {
                            CheckUpdateBean data = result.getData();
                            String currentVersion = BuildConfig.VERSION_NAME;
                            if (data != null) {
                                //当前版本小于 线上版本  提示更新
                                if (AndroidUtil.compareVersion(currentVersion, data.getAndroidNewVersion()) < 0) {
                                    if (!TextUtils.isEmpty(data.getAndroidUpdateDescription())) {
                                        String arr[] = new String[1];
                                        arr[0] = data.getAndroidUpdateDescription();
                                        AppUpdateManager.Builder builder = new AppUpdateManager.Builder(MainActivity.this);
                                        builder.apkUrl(data.getApkUrl())
                                                .updateContent(arr)
                                                .updateForce(false)
                                                .build();
                                    } else {
                                        ToastUtil.showShort("版本更新，更新提示内容为空");
                                    }

                                }
                            }

                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
//                        DialogHelper.dismissProgressDialog();
//                        ToastUtil.showErrorNet(LoginActivity.this);
                    }
                });
    }


    @Override
    protected void onResume() {
        super.onResume();
        Log.d("Debug", "到达onresume中");
//
    }


    @OnClick({R.id.nav_home_tab, R.id.nav_todaypolicy_tab, R.id.nav_mine_tab})
    public void onClick(View v) {
        switch (v.getId()) {
            //主页
            case R.id.nav_home_tab:
                setSelect(0);
                break;
            //今日报单
            case R.id.nav_todaypolicy_tab:
                startActivity(new Intent(MainActivity.this, ReclarationActivity.class));
                break;
            // 我的页面
            case R.id.nav_mine_tab:
                setSelect(1);
                break;
        }
    }

    public void setSelect(int i) {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        hideFragments(ft);
        resetImgs();
        selindex = i;
        switch (i) {
            case 0:
                if (mHomeFragment == null) {
                    mHomeFragment = new HomeFragment();
                    ft.add(R.id.main_content, mHomeFragment, FRAGMENT_TAG[i]).commit();
                } else {
                    ft.show(mHomeFragment);
                    ft.commitAllowingStateLoss();
                }
                navHomeImg.setImageResource(R.mipmap.shouye);
                navHomeText.setTextColor(getResources().getColor(R.color.theme_color));
                break;

            case 1:
                if (mMineFragment == null) {
                    mMineFragment = new MineFragment();
                    ft.add(R.id.main_content, mMineFragment, FRAGMENT_TAG[i]).commit();
                } else {
                    ft.show(mMineFragment);
                    ft.commitAllowingStateLoss();
                }
                navMineImg.setImageResource(R.mipmap.wode);
                navMineText.setTextColor(getResources().getColor(R.color.theme_color));
                break;

        }
//
    }

    private void hideFragments(FragmentTransaction ft) {
        if (mHomeFragment != null) {
            ft.hide(mHomeFragment);
        }

        if (mMineFragment != null) {
            ft.hide(mMineFragment);
        }

    }

    private void resetImgs() {

        //没有选中的图片样式
        navHomeImg.setImageResource(R.mipmap.shouye);
        navMineImg.setImageResource(R.mipmap.wode);

        navHomeText.setTextColor(getResources().getColor(R.color.theme_color));
        navMineText.setTextColor(getResources().getColor(R.color.theme_color));
//
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt(PRV_SELINDEX, selindex);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected int getNormalLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected int getErrorLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected ChoiceAnchorsPresenter createPresenter() {
        return new ChoiceAnchorsPresenter(this, this);
    }

    @Override
    protected void initViewsAndEvents() {
        //主页不允许左滑返回
        mSwipeBackLayout.setEnableGesture(false);
        Unbinder mUnbinder = ButterKnife.bind(this);

        //设置状态栏
        StatusBarUtil.transparencyBar(this);
        StatusBarUtil.StatusBarLightMode(this);
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.commit();
    }

    @Override
    public void requestFailed(String message) {

    }

}
